package com.example.sources.tomcat;

import org.apache.catalina.Context;
import org.apache.catalina.Host;
import org.apache.catalina.Wrapper;
import org.apache.catalina.startup.Tomcat;

/**
 *
 * @author hengyunabc
 *
 */
public class ContainStart {

public static void tomcatStart() throws Exception{


		String hostName = "localhost";
		int port = 8080;
		String contextPath = "";

		String tomcatBaseDir = TomcatUtil.createTempDir("tomcat", port).getAbsolutePath();
		String contextDocBase = TomcatUtil.createTempDir("tomcat-docBase", port).getAbsolutePath();

		Tomcat tomcat = new Tomcat();
		tomcat.setBaseDir(tomcatBaseDir);

		tomcat.setPort(port);
		tomcat.setHostname(hostName);

		Host host = tomcat.getHost();

		Context context = tomcat.addWebapp(host, contextPath, contextDocBase, new EmbededContextConfig());
		Wrapper defaultServlet = context.createWrapper();
		defaultServlet.setName("dispatcherServlet");
		defaultServlet.setServletClass("com.example.sources.servlet.DispatcherServlet");
		defaultServlet.addInitParameter("debug", "0");
		defaultServlet.addInitParameter("listings", "false");
		defaultServlet.setLoadOnStartup(1);
		// Otherwise the default location of a Spring DispatcherServlet cannot be set
		defaultServlet.setOverridable(true);
		context.addChild(defaultServlet);
		context.addServletMapping("/*", "dispatcherServlet");
//		context.addServletMapping("*.html", "default");

		context.setJarScanner(new EmbededStandardJarScanner());

		ClassLoader classLoader = ContainStart.class.getClassLoader();
		context.setParentClassLoader(classLoader);

		// context load WEB-INF/web.xml from classpath
//		context.addLifecycleListener(new WebXmlMountListener());


		tomcat.start();
		tomcat.getServer().await();
	}
}
